<?php
/**
 * Created by PhpStorm.
 * UsersF: Mloong
 * Date: 2018/12/3
 * Time: 9:05
 */

namespace app\api\controller\v1;

use app\admin\model\Account;
use app\api\controller\BaseController;
use app\api\service\AliMessage;
use app\api\service\MobileService;
use app\api\service\RedisService;
use app\api\validate\Mobile;
use app\api\validate\Yzmcode;
use app\api\validate\YzmValidate;
use app\lib\exception\MessageException;
use Driver\Cache\Redis;
use think\App;
use think\facade\Request;

class Message extends BaseController
{
    private $account_info;

    /**
     * 通过message来自动获取不同短信接口
     * @param $phone
     * @param $logo
     * @throws MessageException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function yzm($phone, $name, $sign=null)
    {
        (new YzmValidate()) ->goCheck();
        $redis_set_key = config('redis.all_sign').$name;
        if(Redis::sismember($redis_set_key, $sign) == false){
            return json(['code'=>300, 'msg' => '该标识已被禁用', 'callUrl' => 'www.lqb2018.cn'], '301');
        }
        $redis_hash_key = config('redis.account').$name;
        $account_info = Redis::hget($redis_hash_key);
        try{
            $message_id = $account_info['message_id'];
        }catch (\Exception $e){
            $model = new Account();
            $account_info = $model->where('name', '=', $name)
                ->find()
                ->toArray();
            # 同步写入redis
            $message_id = $account_info['message_id'];
            Redis::hMset($redis_hash_key, $account_info);
        }
        $this->account_info = $account_info;
        if($message_id == 0){
            $result = $this->_yzm($phone, $account_info['company_name']);
        }
        if($message_id == 1){
            $result = $this->a_li_yzm($phone, $sign);
        }
        return $result;
    }


    # 判断并记录注册发送过来的手机号码
    # 随机生成验证码并写入redis-hash，有效期为一分钟
    public function Message($phone)
    {
        $result = MobileService::findMobile($phone);
        if($result){
            return json([
               'code' => 301,
                'msg' => 'Already registered | 已经注册'
            ]);
        }
       // (new Mobile())->goCheck();
        # 随机生成四位数 获取手机号码  发送get请求
        $code = rand(1000, 9999);
        $url = "http://61.129.57.153:7891/mt?un=400141&pw=400141&da={$phone}&sm=【小银】您好，您的验证码是{$code},有效期为5分钟。&dc=15&rd=1&tf=3&rf=2";
        $result = json_decode(get($url),true);
        if(!$result['success']){
            throw new MessageException([
               'success' => false,
               'code' => 404,
               'msg' =>  $result['f'] ?? 'Failed to get verification code | 获取验证码失败'
            ]);
        }
        # 成功则写入redis-hash
        $redis = new RedisService();
        $result = $redis->setMessage($phone,$code);
        if(!$result){
            throw new MessageException([
                'success' => false,
                'code' => 300,
                'msg' =>  '验证码写入缓存失败'
            ]);
        }
        return json([
            'success' => true,
            'code' => 200,
        ]);
    }
    # 检查验证码是否过期
    public function checkMessageTime($phone,$code,$from='微信')
    {
        # 再一次判断
        $result = MobileService::findMobile($phone);
        if($result){
            return json([
                'code' => 301,
                'msg' => 'Already registered | 已经注册'
            ]);
        }
        # 先判断验证码是否已经过期  没有过期则和redis做判断
        $redis = new RedisService();
        $redis_code =  $redis->checkMessage($phone);
        if(!($code === $redis_code)){
            return json([
                'success' => false,
                'code' => 404,
                'msg' => "Verification code is invalid | 验证码有效期失效"
            ]);
        }
        $result = MobileService::createMobileList($phone,ip(),$from);
        return json([
            'success' => true,
            'code' => 200,
            'msg' => $result
        ]);
    }
    # 诺尔短信验证码接口
    private function _yzm($phone, $company_name)
    {
        # 随机生成四位数 获取手机号码  发送get请求
        $code = rand(1000, 9999);
        $url = "http://61.129.57.153:7891/mt?un=400141&pw=400141&da={$phone}&sm=【{$company_name}】您好，您的验证码是{$code},有效期为5分钟。&dc=15&rd=1&tf=3&rf=2";
        $result = json_decode(get($url),true);
        if(!$result['success']){
            throw new MessageException([
                'success' => false,
                'code' => 400,
                'errorCode' => 3001,
                'msg' =>  $result['f'] ?? 'Failed to get verification code | 获取验证码失败'
            ]);
        }
        # 成功则写入redis-hash
        $redis = new RedisService();
        $result = $redis->setMessage($phone,$code);
        if(!$result){
            throw new MessageException([
                'success' => false,
                'code' => 400,
                'errorCode' => 3001,
                'msg' =>  '验证码发送失败|验证码写入缓存失败'
            ]);
        }

        # 把注册所有的号码添加到redis
        $key = config('redis.phone_yzm').$this->account_info['name'];
        Redis::sAdd($key, $phone);

        return json([
            'success' => true,
            'msg' => '验证码发送成功',
            'code' => 200,
        ]);
    }
    # 验证码验证码
    public function checkYzm($phone, $code, $name)
    {
        (new Yzmcode()) -> goCheck();
        $redis = new RedisService();
        $redis_code =  $redis->checkMessage($phone);
        if($code !== $redis_code){

            throw new MessageException([
                'success' => false,
                'code' => 400,
                'errorCode' => 3002,
                'msg' => "Verification code is invalid | 验证码错误"
            ]);
        }
        if($redis_code === false){
            throw new MessageException([
                'success' => false,
                'code' => 400,
                'errorCode' => 3003,
                'msg' => "Verification code error | 验证码有效期失效"
            ]);
        }
        $redis->delMessage($phone);
        $key = config('redis.phone_yzm').$name;
        Redis::sRm($key, $phone);

        return json([
            'success' => true,
            'code' => 200,
        ]);
    }

    # 阿里云短信接口
    private function a_li_yzm($phone, $sign)
    {
        $liMessage = new AliMessage();
        $result = $liMessage->set_message($phone, $this->account_info, $sign);
        return json($result);
    }

    public function testMessage($phone)
    {
        (new YzmValidate()) ->goCheck();
        $redis_key = config('redis.test_message').$phone;
        if(Redis::FindKeys($redis_key)){
           return json([
               'error_code' => -1,
               'msg' => '验证码已发送，如果您未收到验证码， 请五分钟后再试'
           ]);
        }
        $liMessage = new AliMessage();
        $liMessage->test_message($phone);
        Redis::set($redis_key, rand(1000, 9999), 300);
        return json([
            'error_code' => 0,
            'msg' => '验证码发送成功'
        ]);
    }

    public function testCheck($phone, $code)
    {
        (new Yzmcode()) -> goCheck();
        $redis = new RedisService();
        $redis_code =  $redis->testCheckMessage($phone);
        if($code !== $redis_code){

            throw new MessageException([
                'success' => false,
                'errorCode' => -2,
                'msg' => "Verification code is invalid | 验证码错误"
            ]);
        }
        if($redis_code === false){
            throw new MessageException([
                'success' => false,
                'errorCode' => -3,
                'msg' => "Verification code error | 验证码有效期失效"
            ]);
        }
        $redis->testDelMessage($phone);
        return json([
            'success' => true,
            'error_code' => 0,
        ]);
    }
}